import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IdDto } from 'src/common/dto/dto';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { Repository } from 'typeorm';
import { CreateNoticeDto, GetNoticeDto, UpdateNoticeDto } from './dto/notice.dto';
import { NoticeEntity } from './entities/notice.entity';
import { equals } from 'ramda';
import { JumpType } from 'src/dictionaries/index.enum';

@Injectable()
export class NoticeService {
  constructor(
    @InjectRepository(NoticeEntity)
    private noticeEntityRepository: Repository<NoticeEntity>,
  ) { }
  async getNoticePage(params: GetNoticeDto) {
    try {
      const {
        title,
        status,
        expirationStart,
        expirationEnd,
        jumpType,
        type,
      } = params;
      const where: GetNoticeDto = {
        title,
        status,
        expirationStart,
        expirationEnd,
        jumpType,
        type,
      };
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const [data, total] = await this.noticeEntityRepository.findAndCount({
        where,
        cache: true,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 创建公告 */
  @UseFilters(new HttpExceptionFilter())
  async createNotice(body: CreateNoticeDto) {
    try {
      const { title, status, content, type, jumpType, expirationStart, expirationEnd, url, articleId } = body;
      if (equals(jumpType, JumpType.ExternalLinks) && !isTrue(url)) {
        throwHttp('跳转链接不能为空');
        return
      }
      const notice = new NoticeEntity();
      notice.title = title;
      notice.status = status;
      notice.content = content;
      notice.type = type;
      notice.jumpType = jumpType;
      notice.expirationStart = expirationStart;
      notice.expirationEnd = expirationEnd;
      if (equals(jumpType, JumpType.ExternalLinks)) {
        notice.url = url;
      }
      const result = await this.noticeEntityRepository.manager.save(notice);
      if (isTrue(result)) {
        return '创建成功';
      }
      return '创建失败';
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 更新公告 */
  @UseFilters(new HttpExceptionFilter())
  async updateNotice(body: UpdateNoticeDto) {
    try {
      const { id, title, status, content, type, jumpType, expirationStart, expirationEnd, url, articleId } = body;
      if (equals(jumpType, JumpType.ExternalLinks) && !isTrue(url)) {
        throwHttp('跳转链接不能为空');
        return
      }
      const noticeInfo = await this.getNoticeInfo({
        id,
      });
      if (!isTrue(noticeInfo)) {
        throwHttp('公告不存在');
        return;
      }
      const parmas: any = {
        title, status, content, type, jumpType, expirationStart, expirationEnd,
      }
      if (equals(jumpType, JumpType.ExternalLinks)) {
        parmas.url = url;
      }
      if (equals(jumpType, JumpType.article)) {
        parmas.articleId = articleId;
      }
      const { affected } = await this.noticeEntityRepository
        .createQueryBuilder()
        .update(NoticeEntity)
        .set(parmas)
        .where('id = :id', { id })
        .execute();
      if (affected) {
        return '更新成功';
      }
      throwHttp('更新失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取公告详情 */
  @UseFilters(new HttpExceptionFilter())
  async getNoticeInfo({ id }) {
    try {
      return await this.noticeEntityRepository.findOne({
        where: { id },
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 删除公告 */
  @UseFilters(new HttpExceptionFilter())
  async deleteNotice({ id }: IdDto) {
    try {
      const data = await this.getNoticeInfo({ id });
      if (!isTrue(data)) {
        throwHttp('公告不存在');
        return;
      }
      await this.noticeEntityRepository.softDelete(id);
      return '删除成功';
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
